namespace Test.ConsoleProgram.Algorithm.Solution
{
    [TestDescription("算法: 0557. 反转字符串中的单词 III")]
    public class No0557_ReverseWords : AbsBaseTestItem
    {
        /*
        给定一个字符串，你需要反转字符串中每个单词的字符顺序，同时仍保留空格和单词的初始顺序。
        */

        public override void OnTest()
        {
            Assert.TestExe(ReverseWords,
                "Let's take LeetCode contest",
                "s'teL ekat edoCteeL tsetnoc");

            Assert.TestExe(ReverseWords_2,
                "Let's take LeetCode contest",
                "s'teL ekat edoCteeL tsetnoc");
        }

        /// <summary>
        /// 自己写的算法 - 运行时间:132ms 内存消耗:30.9MB
        /// </summary>
        public string ReverseWords(string s)
        {
            char[] carr = s.ToCharArray();
            int n = carr.Length;
            int l = 0, r = 0;
            for (int i = 0; i < n; i++)
            {
                char cv = carr[i];
                if (i == n - 1)
                {
                    r = n - 1;
                }
                else if (cv != ' ')
                {
                    r = i;
                    continue;
                }
                while (l < r)
                {
                    char center = carr[l];
                    carr[l] = carr[r];
                    carr[r] = center;
                    l++;
                    r--;
                }
                l = i + 1;
                r = i;
            }
            return new string(carr);
        }

        /// <summary>
        /// LeetCode 官网 方法二：原地解法 - 运行时间:116ms 内存消耗:30.9MB
        /// </summary>
        public string ReverseWords_2(string s)
        {
            char[] carr = s.ToCharArray();
            int length = carr.Length;
            int i = 0;
            while (i < length)
            {
                int start = i;
                while (i < length && s[i] != ' ')
                {
                    i++;
                }
                int left = start, right = i - 1;
                while (left < right)
                {
                    char tmp = s[left];
                    carr[left] = s[right];
                    carr[right] = tmp;
                    left++;
                    right--;
                }
                while (i < length && s[i] == ' ')
                {
                    i++;
                }
            }
            return new string(carr);
        }
    }
}
